package com.summer.halfSyncAsync;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Future;


public class SampleAsyncTask extends AsyncTask<String> {
	
	public static void main(String[] args) {
		SampleAsyncTask task = new SampleAsyncTask();
		List<Future<String>> results = new LinkedList<Future<String>>();
		try {
			results.add(task.doSomething("Half-sync/Half-async", 1));
			for(int i=2;i<=100;i++)
			results.add(task.doSomething("Pattern"+i, i));
			
			for(Future<String> result : results){
				System.out.println(Thread.currentThread().getName()+"--result:"+result.get());
			}
			Thread.sleep(200);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	@Override
	protected String doInBackground(Object... params) {
		
		
		String message = (String) params[0];
		int sequence = (int) params[1];
		System.out.println(Thread.currentThread().getName()+"--doInBackground:"+message);
		

//		try {
//			Thread.sleep(2000);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
		
		return "message "+sequence+":"+message;
	}
	
	@Override
	protected void onPreExecute(Object... params) {
		String message = (String) params[0];
		int sequence = (int) params[1];
		System.out.println(Thread.currentThread().getName()+"--onPreExecute:["+sequence+"]"+message);
	}

	public Future<String> doSomething(String message,int sequence){
		if(sequence < 0){
			throw new IllegalArgumentException("Invalid sequence:"+sequence);
		}
		return dispatch(message,sequence);
	}
}
